<!DOCTYPE html>


<html lang="zh-CN">
  

    <head>
      <meta charset="utf-8" />
       
      <meta name="keywords" content="ES6、JS" />
       
      <meta name="description" content="ES6、JS" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>commonjs 规范 |  君书</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css"
      />
      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    <link rel="alternate" href="/atom.xml" title="君书" type="application/atom+xml">
</head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-commonjs-规范"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  commonjs 规范
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2022/06/22/commonjs-%E8%A7%84%E8%8C%83/" class="article-date">
  <time datetime="2022-06-22T09:05:01.000Z" itemprop="datePublished">2022-06-22</time>
</a>   
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">999</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">3 分钟</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>Nodejs 采用的是 commonJs 规范约定模块规则。commonjs 规定模块划分为 <code>引用、定义、标识</code> 三部分。</p>
<span id="more"></span>

<h2 id="1-模块引用"><a href="#1-模块引用" class="headerlink" title="1. 模块引用"></a>1. 模块引用</h2><p>使用 require 导入其他模块。<code>require</code> 属性基本功能是：读入并且执行一个模块文件，返回模块文件的 <code>module.exports</code> 导出的对象。</p>
<table>
<thead>
<tr>
<th>API</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>resolve</td>
<td>返回模块文件的绝对路径。查找模块，但不加载</td>
</tr>
<tr>
<td>main</td>
<td>Node.js 进程启动时加载的入口脚本，如果程序的入口点不是 CommonJS 模块，则为 undefined（可以理解为返回的是父模块。入口文件的父模块即本身模块）</td>
</tr>
<tr>
<td>extensions</td>
<td>依旧不同后缀名执行解析操作</td>
</tr>
</tbody></table>
<h2 id="2-模块定义"><a href="#2-模块定义" class="headerlink" title="2. 模块定义"></a>2. 模块定义</h2><p>任意一个文件就是一个模块，具有独立作用域，模块内可以直接使用 <code>module</code> 属性。</p>
<table>
<thead>
<tr>
<th>API</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>id</td>
<td>模块标识符，一般是一个绝对路径</td>
</tr>
<tr>
<td>filename</td>
<td>文件模块的绝对路径</td>
</tr>
<tr>
<td>loaded</td>
<td>返回 boolean，表示模块是否完成加载</td>
</tr>
<tr>
<td>parent</td>
<td>返回对象，存放调用当前模块的模块</td>
</tr>
<tr>
<td>children</td>
<td>返回数组，存放当前模块调用的其他模块</td>
</tr>
<tr>
<td>exports</td>
<td>返回当前模块需要暴露的内容</td>
</tr>
<tr>
<td>paths</td>
<td>返回数组，存放不同目录下的 node_modules 路径</td>
</tr>
</tbody></table>
<p>exports 是 Nodejs 为了使用方便定义的变量，它指向 module.exports 的空间。可以对 exports 内的属性赋值，不能对 exports 赋值。</p>
<p><img src="https://cdn.nlark.com/yuque/0/2022/png/26238530/1655798110895-5ee39fa1-cffd-4eae-84b5-a35dad00222e.png#clientId=uf7bd9615-307f-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=303&id=ub4ab57f7&margin=%5Bobject%20Object%5D&name=image.png&originHeight=605&originWidth=1017&originalType=binary&ratio=1&rotation=0&showTitle=false&size=166322&status=done&style=none&taskId=u942da01e-c498-47d8-bd4d-af742423ae3&title=&width=508.5" alt="image.png"></p>
<h2 id="3-模块标识"><a href="#3-模块标识" class="headerlink" title="3. 模块标识"></a>3. 模块标识</h2><p>将模块 ID 传入 require 实现目标模块定位。</p>
<h2 id="4-commonjs-原理"><a href="#4-commonjs-原理" class="headerlink" title="4. commonjs 原理"></a>4. commonjs 原理</h2><p>commonjs 是同步加载（源码以 <code>fs.readFileSync()</code> 读取文件内容）</p>
<h3 id="1-模块分类以及加载流程"><a href="#1-模块分类以及加载流程" class="headerlink" title="1.  模块分类以及加载流程"></a>1.  模块分类以及加载流程</h3><h4 id="1-模块分类"><a href="#1-模块分类" class="headerlink" title="1. 模块分类"></a>1. 模块分类</h4><ol>
<li>内置模块（核心模块）</li>
</ol>
<p>​    Node 源码编译时写入到二进制文件中（进程启用时，核心模块已经存在于内存中）</p>
<ol start="2">
<li>文件模块</li>
</ol>
<p>​    代码运行时，动态加载（第三方包，自定义模块等）</p>
<h4 id="2-加载流程"><a href="#2-加载流程" class="headerlink" title="2. 加载流程"></a>2. 加载流程</h4><p>路径分析（路径（自定义文件）和非路径（核心或者第三方包） path.sep）-&gt; 文件定位（文件后缀名 .js/son/node/文件夹） -&gt; 编译执行（创建新对象，按路径载入，执行编译执行）</p>
<p>针对文件定位若文件没有后缀名：</p>
<ol>
<li>查找当前目录下的 <code>package.json</code> 文件，使用 <code>JSON.parse()</code> 解析</li>
<li>找到其中的 <code>main</code> 字段值</li>
<li>若 <code>main</code> 无后缀，则进行后缀补充操作 <code>.js/json/node</code></li>
<li>后缀补充后若仍旧查不到文件，则将 index 做为目标模块中的具体文件名进行查找。循环 module.paths 进行 1-4</li>
</ol>
<p><code>注意点：</code></p>
<p><strong>加载模块时存在的缓存优先原则，提高模块加载速度。</strong> 在路径解析完成后，根据路径到缓存中查找：</p>
<ol>
<li>当前模块不存在，则经历一次完整的加载流程</li>
<li>模块加载完成后，使用路径作为索引进行缓存</li>
</ol>
<p>所以完整的加载流程核心逻辑是：<code>路径分析 -&gt; 缓存优先 -&gt; 文件定位 -&gt; 编译执行</code></p>
<ol>
<li>路径分析：根据传入路径拼接出绝对路径  <code>module._resolveFilename</code></li>
<li>缓存优先：根据绝对路径到缓存中查找资源。若查找到，就不会再往下走，直接返回 module.exports</li>
<li>文件定位：根据绝对路径进行文件的定位，并获取文件的内容 <code>module.load</code></li>
<li>编译执行：将文件内容包裹成为接收 <code>exports/require/module/__filename/__dirname</code> 形参的函数字符串，通过 vm 实现独立运行的沙箱环境并使用 call 调用 。<code>并将 module.exports 的结果返回</code>。<code>module._compile</code></li>
</ol>
<h3 id="2-VM-模块使用"><a href="#2-VM-模块使用" class="headerlink" title="2.  VM 模块使用"></a>2.  VM 模块使用</h3><p>Nodejs 内置核心模块。创建独立运行的沙箱环境。（在 A 模块中执行 B 模块的内容）</p>
<p>将字符转为执行函数的方法：</p>
<ol>
<li><p><code>eval()</code> ： 作用域不独立</p>
</li>
<li><p><code>new Function()</code>：定义麻烦</p>
</li>
<li><p><code>vm 机制</code>：沙箱</p>
<p>在当前 <code>global</code> 的上下文中运行 code 并返回结果。 运行代码无权访问局部作用域，但可以访问当前 <code>global</code> 对象</p>
</li>
</ol>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>版权声明： </strong>
          
          本博客所有文章除特别声明外，著作权归作者所有。转载请注明出处！
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://xiaofujun.gitee.io/2022/06/22/commonjs-%E8%A7%84%E8%8C%83/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/nodejs/" rel="tag">nodejs</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2022/06/22/%E6%A8%A1%E5%9D%97%E5%8C%96/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            模块化
          
        </div>
      </a>
    
    
      <a href="/2022/06/22/%E4%BA%8B%E4%BB%B6%E7%8E%AF/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">事件环</div>
      </a>
    
  </nav>

  
   
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2022
        <i class="ri-heart-fill heart_icon"></i> 小付君
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="君书"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>